<template>
  <a-modal
    v-model:open="visible"
    title="批量创建图片"
    width="600px"
    :footer="null"
    :destroy-on-close="true"
    @cancel="handleCancel"
  >
    <div id="addPictureBatchModal">
      <!-- 保存位置提示 -->
      <div style="margin-bottom: 24px">
        <a-alert 
          message="批量创建图片" 
          description="批量创建的图片将统一保存到公共图库，所有用户都可以浏览和使用"
          type="info"
          show-icon
        />
      </div>
      
      <!-- 批量上传表单 -->
      <a-form name="formData" layout="vertical" :model="formData" @finish="handleSubmit">
        <a-form-item name="searchText" label="关键词" :rules="[{ required: true, message: '请输入关键词' }]">
          <a-input v-model:value="formData.searchText" placeholder="请输入关键词" allow-clear />
        </a-form-item>
        <a-form-item name="count" label="抓取数量" :rules="[{ required: true, message: '请输入抓取数量' }]">
          <a-input-number
            v-model:value="formData.count"
            placeholder="请输入数量"
            style="width: 100%"
            :min="1"
            :max="50"
            allow-clear
          />
          <div style="margin-top: 4px; color: #666; font-size: 12px">
            建议一次上传不超过 30 张图片，避免超时
          </div>
        </a-form-item>
        <a-form-item name="namePrefix" label="名称前缀">
          <a-input
            v-model:value="formData.namePrefix"
            placeholder="请输入名称前缀，会自动补充序号"
            allow-clear
          />
          <div style="margin-top: 4px; color: #666; font-size: 12px">
            如不填写，将使用关键词作为前缀
          </div>
        </a-form-item>
        
        <!-- 进度显示 -->
        <div v-if="uploadProgress.show" style="margin: 16px 0">
          <a-divider orientation="left">上传进度</a-divider>
          <a-progress 
            :percent="uploadProgress.percent" 
            :status="uploadProgress.status"
            :stroke-color="uploadProgress.status === 'exception' ? '#ff4d4f' : '#1890ff'"
          />
          <div style="margin-top: 8px; color: #666; font-size: 12px">
            {{ uploadProgress.text }}
          </div>
        </div>
        
        <a-form-item>
          <a-space style="width: 100%; justify-content: flex-end">
            <a-button @click="handleCancel" :disabled="loading">取消</a-button>
            <a-button type="primary" html-type="submit" :loading="loading">
              {{ loading ? '上传中...' : '开始批量上传' }}
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { reactive, ref, watchEffect } from 'vue'
import { message } from 'ant-design-vue'
import { uploadPictureByBatchUsingPost } from '@/api/pictureController.ts'

interface Props {
  open?: boolean
  onSuccess?: () => void
  onCancel?: () => void
}

const props = defineProps<Props>()

const visible = ref(false)
const loading = ref(false)

// 表单数据
const formData = reactive<API.PictureUploadByBatchRequest>({
  count: 10,
  searchText: '',
  namePrefix: ''
})

// 上传进度
const uploadProgress = reactive({
  show: false,
  percent: 0,
  status: 'active' as 'active' | 'success' | 'exception',
  text: ''
})

// 监听props.open变化
watchEffect(() => {
  visible.value = props.open || false
})

/**
 * 提交表单
 * @param values
 */
const handleSubmit = async (values: any) => {
  loading.value = true
  uploadProgress.show = true
  uploadProgress.percent = 0
  uploadProgress.status = 'active'
  uploadProgress.text = '正在抓取图片...'
  
  try {
    // 模拟进度更新
    const progressInterval = setInterval(() => {
      if (uploadProgress.percent < 90) {
        uploadProgress.percent = Math.min(90, uploadProgress.percent + Math.random() * 10)
        uploadProgress.percent = Math.round(uploadProgress.percent * 10) / 10 // 保留1位小数
        uploadProgress.text = `正在上传图片... ${uploadProgress.percent.toFixed(1)}%`
      }
    }, 500)
    
    // 批量上传请求数据（保存到公共图库）
    const requestData = {
      ...formData,
    }
    
    const res = await uploadPictureByBatchUsingPost(requestData)
    
    clearInterval(progressInterval)
    
    // 操作成功
    if (res.data.code === 0 && res.data.data) {
      uploadProgress.percent = 100
      uploadProgress.status = 'success'
      uploadProgress.text = `批量上传完成！成功上传 ${res.data.data} 张图片`
      
      message.success(`创建成功，共 ${res.data.data} 条`)
      
      // 延迟关闭弹窗，让用户看到成功信息
      setTimeout(() => {
        handleCancel()
        props.onSuccess?.()
      }, 1500)
    } else {
      uploadProgress.status = 'exception'
      uploadProgress.text = '上传失败：' + res.data.message
      message.error('创建失败，' + res.data.message)
    }
  } catch (error) {
    uploadProgress.status = 'exception'
    uploadProgress.text = '上传失败，请检查网络连接'
    message.error('上传失败，请重试')
  } finally {
    loading.value = false
  }
}

/**
 * 取消操作
 */
const handleCancel = () => {
  visible.value = false
  // 重置状态
  formData.searchText = ''
  formData.namePrefix = ''
  formData.count = 10
  loading.value = false
  uploadProgress.show = false
  uploadProgress.percent = 0
  uploadProgress.status = 'active'
  uploadProgress.text = ''
  
  props.onCancel?.()
}

// 暴露打开弹窗的方法
const openModal = () => {
  visible.value = true
}

defineExpose({
  openModal
})
</script>

<style scoped>
#addPictureBatchModal {
  max-width: 100%;
}

/* 黑色模式适配 */
[data-theme="dark"] #addPictureBatchModal {
  color: #e5e7eb;
}

[data-theme="dark"] #addPictureBatchModal .ant-card {
  background: rgba(55, 65, 81, 0.8) !important;
  border-color: rgba(75, 85, 99, 0.5) !important;
}

[data-theme="dark"] #addPictureBatchModal .ant-card:hover {
  border-color: rgba(14, 165, 233, 0.6) !important;
}

[data-theme="dark"] #addPictureBatchModal .ant-card .ant-card-head-title {
  color: #e5e7eb !important;
}

[data-theme="dark"] #addPictureBatchModal .ant-card .ant-card-body p {
  color: #9ca3af !important;
}

[data-theme="dark"] #addPictureBatchModal .ant-typography {
  color: #9ca3af !important;
}

[data-theme="dark"] #addPictureBatchModal .ant-form-item-label > label {
  color: #e5e7eb !important;
}

[data-theme="dark"] #addPictureBatchModal .ant-input,
[data-theme="dark"] #addPictureBatchModal .ant-select-selector,
[data-theme="dark"] #addPictureBatchModal .ant-input-number {
  background: rgba(55, 65, 81, 0.8) !important;
  border-color: rgba(75, 85, 99, 0.5) !important;
  color: #e5e7eb !important;
}

[data-theme="dark"] #addPictureBatchModal .ant-input:hover,
[data-theme="dark"] #addPictureBatchModal .ant-input-number:hover {
  border-color: rgba(14, 165, 233, 0.6) !important;
}

[data-theme="dark"] #addPictureBatchModal .ant-input:focus,
[data-theme="dark"] #addPictureBatchModal .ant-input-focused,
[data-theme="dark"] #addPictureBatchModal .ant-input-number:focus {
  border-color: #0ea5e9 !important;
  box-shadow: 0 0 0 2px rgba(14, 165, 233, 0.2) !important;
}

[data-theme="dark"] #addPictureBatchModal .ant-input::placeholder {
  color: #9ca3af !important;
}

[data-theme="dark"] #addPictureBatchModal .ant-divider-horizontal.ant-divider-with-text {
  color: #e5e7eb !important;
}

[data-theme="dark"] #addPictureBatchModal .ant-divider-horizontal.ant-divider-with-text::before,
[data-theme="dark"] #addPictureBatchModal .ant-divider-horizontal.ant-divider-with-text::after {
  border-color: rgba(75, 85, 99, 0.5) !important;
}
</style>
